import pymysql
import random

# 数据库连接配置
DB_CONFIG = {
    'host': 'localhost',
    'port': 3306,
    'user': 'root',
    'password': 'wozui666',
    'database': '12',
    'charset': 'utf8mb4'
}

# 预定义的标签池（不超过20种）
LABELS_POOL = [
    '游戏', '美女', '陪玩', '娱乐', '生活', '搞笑', '萌宠', '音乐', 
    '舞蹈', '美食', '旅行', '运动', '科技', '动漫', '影视', '时尚', 
    '美妆', '健康', '情感', '其他'
]

def get_db_connection():
    """创建数据库连接"""
    return pymysql.connect(**DB_CONFIG)

def generate_labels():
    """随机生成3-5个标签"""
    return random.sample(LABELS_POOL, k=random.randint(3, 5))

def fill_empty_labels():
    """给 videos 表中 labels 为空的记录补充标签"""
    conn = get_db_connection()
    try:
        with conn.cursor() as cursor:
            # 找出 labels 为空的记录
            cursor.execute("SELECT vid FROM videos WHERE labels IS NULL OR labels = ''")
            rows = cursor.fetchall()

            if not rows:
                print("没有需要补充标签的数据")
                return

            update_sql = "UPDATE videos SET labels = %s WHERE vid = %s"
            
            for (vid,) in rows:
                labels = generate_labels()
                labels_str = ','.join(labels)
                cursor.execute(update_sql, (labels_str, vid))
            
            conn.commit()
            print(f"成功更新 {len(rows)} 条记录的标签")
    except Exception as e:
        conn.rollback()
        print(f"更新失败: {str(e)}")
    finally:
        conn.close()

if __name__ == "__main__":
    fill_empty_labels()
